<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }" class="outer">
    <template #header>
      <el-button type="primary" icon="ele-Plus" @click="add">添加</el-button>
    </template>
    <el-table :data="trademarkList" border stripe v-loading="loading">
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column label="品牌名称" prop="tmName" />
      <el-table-column label="图片logo" prop="logoUrl">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" width="100" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            type="warning"
            size="small"
            icon="ele-Edit"
            @click="edit(row)"
            >修改</el-button
          >
          <el-popconfirm
            title="你确定要删除吗???"
            @confirm="deleteTrademark(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="small" icon="ele-Delete"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :style="{ marginTop: '20px' }"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout=" sizes, prev, pager, next, jumper,total"
      :total="totalNum"
    />
    <el-dialog
      :title="tmInfo.id ? '修改品牌' : '添加商品'"
      v-model="dialogVisible"
      width="60%"
    >
      <el-form
        label-width="80px"
        :inline="false"
        :rules="rules"
        :model="tmInfo"
        ref="formEl"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="tmInfo.tmName" />
        </el-form-item>
        <el-form-item label="品牌Logo" v-model="tmInfo.logoUrl" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${baseUrl}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><ele-Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addOrUpdateTrademark">{{
            tmInfo.id ? "修改" : "添加"
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref, watch } from "vue";
import {
  reqAddTrademark,
  reqDeleteTrademark,
  reqTrademarkInfo,
  reqUpdateTradmark,
  type trademarkItemType,
  type trademarkListType,
} from "../../../api/trademark";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules, UploadProps } from "element-plus";
export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
// 定义初始化数据
const currentPage = ref(1);
const pageSize = ref(5);
const totalNum = ref(0);

// 定义初始化loading
const loading = ref(false);

// 定义初始化品牌logo
const imageUrl = ref("");
// 定义初始化dialog弹出
const dialogVisible = ref(false);

// dialog区域
//定义一个上传接口的 代理前缀
const baseUrl = import.meta.env.VITE_API_URL;
// 图片上传成功后的回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  // 收集地址
  tmInfo.value.logoUrl = response.data;
};
// 上传图片前的回调
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // 字符串方法（startsWith("")）：以xxx为开头
  if (!rawFile.type.startsWith("image/")) {
    ElMessage.error("上传的不是图片类型！！！");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("上传图片的大小不能大于10MB!");
    return false;
  }
  return true;
};

//初始化品牌列表的数据
const trademarkList = ref<trademarkListType>([]);
// 封装请求数据
const getTrademarkList = async () => {
  try {
    loading.value = true;
    const res = await reqTrademarkInfo(currentPage.value, pageSize.value);
    loading.value = false;
    // console.log(res);
    trademarkList.value = res.records;
    totalNum.value = res.total;
  } catch (e: any) {
    ElMessage.error("品牌列表请求失败:" + e.message);
  }
};
onMounted(() => {
  getTrademarkList();
});

// 页码发生改变重新请求数据
watch([currentPage, pageSize], () => {
  getTrademarkList();
  // 数据改变回到顶部
  window.scrollTo(0, 0);
});

//初始化收集用户新增品牌的数据
const tmInfo = ref<trademarkItemType>({
  tmName: "",
  logoUrl: "",
});

//用户点击新增按钮的事件回调函数
const add = () => {
  // 进入添加页面清除上次的表单校验
  formEl.value?.clearValidate();
  dialogVisible.value = true;

  // 重置收集用户表单的tmInfo
  tmInfo.value = {
    tmName: "",
    logoUrl: "",
  };
  // 清空本地缓存（清空图片）
  imageUrl.value = "";
};

const formEl = ref<FormInstance>();

// 收集用户信息后 新增品牌的事件回调函数
const addOrUpdateTrademark = async () => {
   // 对表单进行整体校验
   try {
    await formEl.value?.validate();
  } catch (e) {
    return;
  }
  if (tmInfo.value.id) {
    // 有id：修改
    try {
      await reqUpdateTradmark(tmInfo.value);
      //关闭弹窗
      dialogVisible.value = false;
      //重新请求
      getTrademarkList();
    } catch (e: any) {
      ElMessage.error("修改品牌失败：" + e.message);
    }
  } else {
    // 没有id：添加
    try {
      await reqAddTrademark(tmInfo.value);
      //关闭弹窗
      dialogVisible.value = false;
      //重新请求
      getTrademarkList();
    } catch (e: any) {
      ElMessage.error("新增品牌失败：" + e.message);
    }
  }
};

//修改品牌事件回调函数
const edit = (row: trademarkItemType) => {
  dialogVisible.value = true;
  //回填数据(拷贝,否则tmInfo和row是同一个地址,tmInfo只要发生改变,则row直接就改变)
  tmInfo.value = { ...row };
  imageUrl.value = row.logoUrl;
};

//删除品牌的事件回调函数
const deleteTrademark = async (id: number) => {
  try {
    await reqDeleteTrademark(id);
    //重新请求
    getTrademarkList();
  } catch (e: any) {
    ElMessage.error("删除失败:" + e.message);
  }
};

// 添加商品的表单校验
const tmNameValidate = (rule: any, value: any, callback: any) => {
  //value就是我们被检验的值,callback不接受参数调用代表放行,接受new Error()代表报错
  const reg = /^.{2,6}$/; // 正则"."  代表匹配任意字符
  if (reg.test(value)) {
    callback();
  } else {
    callback(new Error("品牌的长度必须是2-6位"));
  }
};
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "品牌名称不能为空", trigger: "blur" },
    { validator: tmNameValidate, trigger: "blur" },
  ],
  logoUrl: [{ required: true, message: "品牌logo不能为空", trigger: "blur" }],
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.outer:deep(.el-dialog) {
  margin-top: 20px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
